package com.beiye.drivertransport.SubActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.frame.view.linearlistview.LinearListView;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.DaiKaoAdapter;
import com.beiye.drivertransport.adapter.HaveTestAdapter;
import com.beiye.drivertransport.bean.DaikaoBean;
import com.beiye.drivertransport.bean.HaveTestBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.OnLineEducationDataBean;
import com.beiye.drivertransport.chart.NewPieChart;
import com.beiye.drivertransport.chart.PieDataEntity;
import com.beiye.drivertransport.examination.ExaminationActivity;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;

import java.util.ArrayList;
import java.util.List;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;
//在线测验
public class OnlineEducationActivity extends TwoBaseAty {

    LinearListView listview_daikao;

    LinearListView listview_havetest;

    ImageView img_online_back;
//    @Bind(R.id.img_online_examination)
//    TextView img_online_examination;

    TextView tv_online;

    NewPieChart pieChart;

    TextView tv_online_comple;

    TextView tv_online_nocomple;

    TextView tv_online_toguo;

    TextView tv_online_notoguo;

    RelativeLayout re_online;

    RelativeLayout re_onlinedata;
 //   ArrayList<LoginUserBean.DataBean.CurUserOrgBean> cusList = new ArrayList<>();

    private int[] mColors = {0xFF26ca51, 0xFFf6c344};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private DaiKaoAdapter messageDaikaoApt;
    private HaveTestAdapter messageHTApt;
//    private PopWindowApt popWindowApt;
//    private PopupWindow mPopWindow;


    @Override
    public int getLayoutId() {
        return R.layout.activity_online_education;

    }

    public void onClick(View view) {
        if (view.getId() == R.id.img_online_back) {
            SharedPreferences sp = getSharedPreferences("OnlineEducationActivity",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.clear();
            edit.commit();
            finish();
        }

    }


    @Override
    public void onBackPressed() {
        SharedPreferences sp = getSharedPreferences("OnlineEducationActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();

        super.onBackPressed();
    }

    @Override
    public void initData() {
        listview_daikao = (LinearListView) findViewById(R.id.listview_online);
        listview_havetest = (LinearListView) findViewById(R.id.listview_online1);
        img_online_back = (ImageView) findViewById(R.id.img_online_back);
        tv_online = (TextView) findViewById(R.id.tv_online_examination);
        pieChart = (NewPieChart) findViewById(R.id.chart);
        tv_online_comple = (TextView) findViewById(R.id.tv_online2);
        tv_online_nocomple = (TextView) findViewById(R.id.tv_online5);
        tv_online_toguo = (TextView) findViewById(R.id.tv_online9);
        tv_online_notoguo = (TextView) findViewById(R.id.tv_online11);
        re_online = (RelativeLayout) findViewById(R.id.re_online);
        re_onlinedata = (RelativeLayout) findViewById(R.id.re_online1);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        //选中公司方法
      //  initCompany();
        Bundle bundle = getIntent().getExtras();
        int mark = bundle.getInt("Mark");
        String orgId = bundle.getString("orgId");
        String orgName = bundle.getString("orgName");
        String personphotoUrl = bundle.getString("personphotoUrl");
        int faceRecgMark = bundle.getInt("faceRecgMark");
        tv_online.setText(orgName);
        SharedPreferences sp = getSharedPreferences("OnlineEducationActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("Mark", mark);
        editor.putInt("faceRecgMark",faceRecgMark);
        editor.putString("personphotoUrl",personphotoUrl);
        editor.commit();
        initListData(orgId,orgName);

        //待考监听
        listview_daikao.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                if (Utils.isFastDoubleClick()) {
                    return;
                }

                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(OnlineEducationActivity.this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(OnlineEducationActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    return;
                }
                SharedPreferences sp = getSharedPreferences("OnlineEducationActivity", Context.MODE_PRIVATE);
                int mark = sp.getInt("Mark", 1);
                if (mark == 0) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(OnlineEducationActivity.this);
                    builder1.setMessage("您已被企业管理员禁用,请联系企业管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();
                    return;
                }
                if (messageDaikaoApt.getItem(position).getOverdueMark() == 1) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(OnlineEducationActivity.this);
                    builder1.setMessage("过期失效");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ;
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();

                } else {
                    showLoadingDialog("");
                    String orgName = sp.getString("orgName", "");
                    int faceRecgMark = sp.getInt("faceRecgMark", 0);
                    String personphotoUrl = sp.getString("personphotoUrl", "");
                    String qptId = messageDaikaoApt.getItem(position).getQptId();
                    Bundle bundle = new Bundle();
                    bundle.putInt("daikaosn", messageDaikaoApt.getItem(position).getSn());
                    bundle.putString("orgName", orgName);
                    bundle.putInt("daikaoqpsn", messageDaikaoApt.getItem(position).getQpSn());
                    bundle.putString("personphotoUrl",personphotoUrl);
                    bundle.putInt("faceRecgMark",faceRecgMark);
                    if(qptId==null)
                    {
                        bundle.putString("qptId", "");
                    }else{
                        bundle.putString("qptId", qptId);
                    }

                    startActivity(ExaminationActivity.class, bundle);
                }

            }
        });
        //已考监听
        listview_havetest.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                if (Utils.isFastDoubleClick()) {
                    return;
                }
                SharedPreferences sp1 = getSharedPreferences("OnlineEducationActivity", Context.MODE_PRIVATE);
                int mark = sp1.getInt("Mark", 1);
                if (mark == 0) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(OnlineEducationActivity.this);
                    builder1.setMessage("您已被企业管理员禁用,请联系企业管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();
                    return;
                }

                Bundle bundle = new Bundle();
                bundle.putInt("havesn", messageHTApt.getItem(position).getSn());
                bundle.putLong("havecreation", messageHTApt.getItem(position).getCreationDate());
                bundle.putInt("haveqpsn", messageHTApt.getItem(position).getQpSn());
                bundle.putString("haveqptName", messageHTApt.getItem(position).getQptName());
                bundle.putString("haveqpName", messageHTApt.getItem(position).getQpName());
                bundle.putInt("havetotalScore", messageHTApt.getItem(position).getTotalScore());
                bundle.putInt("havepassScore", messageHTApt.getItem(position).getPassScore());
                bundle.putInt("havescore", messageHTApt.getItem(position).getScore());
                bundle.putInt("havepassMark", messageHTApt.getItem(position).getPassMark());
                bundle.putLong("testEndDate", messageHTApt.getItem(position).getTestEndDate());
                bundle.putString("signPicUrl", messageHTApt.getItem(position).getSignPicUrl());

                /**
                 * 此处要传这条已考的所有数据
                 */
                startActivity(HaveTestActivity.class, bundle);


            }
        });
    }


 //   private void initCompany() {
//        LoginUserBean userInfo = UserManger.getUserInfo();
//        LoginUserBean.DataBean data = userInfo.getData();
//        if (data == null) {
//            return;
//        }
//
//        List<LoginUserBean.DataBean.CurUserOrgBean> curuserOrglist = data.getCur_userOrg();
//
//        if (curuserOrglist.size() == 0) {
//            img_online_examination.setVisibility(View.INVISIBLE);
//            return;
//        }
//        cusList.clear();
//        for (int i = 0; i < curuserOrglist.size(); i++) {
//            if (curuserOrglist.get(i).getMark() != 2) {
//                cusList.add(curuserOrglist.get(i));
//            }
//        }
//        String orgName = cusList.get(0).getOrgName();
//        String orgId = cusList.get(0).getOrgId();
//        int mark = cusList.get(0).getMark();

//        popWindowApt = new PopWindowApt(OnlineEducationActivity.this, cusList, R.layout.popwindow_item_layout);
//        if (popWindowApt.getCount() == 1) {
//            img_online_examination.setVisibility(View.INVISIBLE);
//        } else {
//            img_online_examination.setVisibility(View.VISIBLE);
//        }


        //        OkGo.get(AppInterfaceConfig.BASE_URL + "vehicle/vehicleOrg/" + userId)     // 请求方式和请求url
//                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String result, Call call, Response response) {
//
//                        CompanyBean companyBean = JSON.parseObject(result, CompanyBean.class);
//                        List<CompanyBean.RowsBean> rows = companyBean.getRows();
//
//
//                        if(rows.size()==0)
//                        {
//                            LoginUserBean userInfo = UserManger.getUserInfo();
//                            String orgName = userInfo.getOrgName();
//                            String orgId = userInfo.getOrgId();
//                            CompanyBean.RowsBean temp = new CompanyBean.RowsBean();
//                            temp.setOrgId(userInfo.getOrgId());
//                            temp.setOrgName(userInfo.getOrgName());
//                            rows.add(temp);
//                            tv_online.setText(orgName);
//                            initListData(orgId);
//                        }else{
//
//                            tv_online.setText(rows.get(0).getOrgName());
//                            initListData(rows.get(0).getOrgId());
//                        }
//
//                    }
//                });

 //   }

//    private void showPopupWindow() {
//        //设置contentView
//        View contentView = LayoutInflater.from(OnlineEducationActivity.this).inflate(R.layout.popwindow_layout, null);
//        mPopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//        //设置各个控件的点击响应
//        ListView lv_company = (ListView) contentView.findViewById(R.id.lv_company);
//        lv_company.setAdapter(popWindowApt);
//        mPopWindow.showAtLocation(tv_online, Gravity.CENTER, 0, 0);
//        lv_company.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                if (popWindowApt != null) {
//
//                    String orgName = popWindowApt.getItem(position).getOrgName();
//                    String orgId = popWindowApt.getItem(position).getOrgId();
//                    int mark = popWindowApt.getItem(position).getMark();
//                    SharedPreferences sp = getSharedPreferences("Mark5", Context.MODE_PRIVATE);
//                    SharedPreferences.Editor editor = sp.edit();
//                    editor.putInt("Mark", mark);
//                    editor.commit();
//                    mPopWindow.dismiss();
//                    tv_online.setText(orgName);
//                    initListData(orgId,orgName);
//                }
//            }
//        });
//    }


    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sp = getSharedPreferences("OnlineEducationActivity",
                Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        String orgName = sp.getString("orgName", "");
        initListData(orgId, orgName);
    }

    public void initListData(String orgId, String orgName) {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();

        SharedPreferences sp = getSharedPreferences("OnlineEducationActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("orgId", orgId);
        editor.putString("orgName", orgName);

        editor.commit();


        new Login().getDaikaoAndHave(userId, orgId,0, 0, 1,10000,this,1);//未考
        new Login().getDaikaoAndHave(userId, orgId, 0,1,1,10000, this, 2);//已考
        new Login().getMonthlyStatisticsOfTestData(userId, orgId, this, 3);//统计数据模块
    }

    @Override
    public void requestData() {

    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            DaikaoBean daikaoBean = JSON.parseObject(result, DaikaoBean.class);
            List<DaikaoBean.RowsBean> daikaorows = daikaoBean.getRows();
            messageDaikaoApt = new DaiKaoAdapter(OnlineEducationActivity.this, daikaorows, R.layout.daikao_item);
            listview_daikao.setAdapter(messageDaikaoApt);
        } else if (what == 2) {
            HaveTestBean haveTestBean = JSON.parseObject(result, HaveTestBean.class);
            List<HaveTestBean.RowsBean> havetestrows = haveTestBean.getRows();
            messageHTApt = new HaveTestAdapter(OnlineEducationActivity.this, havetestrows, R.layout.havetest_item);
            listview_havetest.setAdapter(messageHTApt);
        } else if (what == 3) {
            OnLineEducationDataBean onLineEducationDataBean = JSON.parseObject(result, OnLineEducationDataBean.class);
            OnLineEducationDataBean.DataBean data = onLineEducationDataBean.getData();

            int finishNo = data.getFinishNo();//完成数
            int notfinishNo = data.getNotfinishNo();//未完成数
            int notPassNo = data.getNotPassNo();//未及格数
            int passNo = data.getPassNo();//及格数
            if (notPassNo == 0 && passNo == 0) {
                re_online.setVisibility(View.VISIBLE);
                re_onlinedata.setVisibility(View.GONE);
                tv_online_comple.setText(finishNo + "次");
                tv_online_nocomple.setText(notfinishNo + "次");
            } else {
                re_online.setVisibility(View.GONE);
                re_onlinedata.setVisibility(View.VISIBLE);
                List<PieDataEntity> dataEntities = new ArrayList<>();
                PieDataEntity entity1 = new PieDataEntity("通过", passNo, mColors[0]);
                PieDataEntity entity2 = new PieDataEntity("未通过", notPassNo, mColors[1]);
                dataEntities.add(entity1);
                dataEntities.add(entity2);
                pieChart.setDataList(dataEntities);
                pieChart.startAnimation(2000);
                tv_online_toguo.setText(passNo + "次");
                tv_online_notoguo.setText(notPassNo + "次");
                tv_online_comple.setText(finishNo + "次");
                tv_online_nocomple.setText(notfinishNo + "次");
            }


        }

        super.onSuccess(result, call, response, what);
    }
}
